<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\command\cdc;

use app\command\BaseWork;
use app\enum\CdcEnum;
use app\enum\NoticeEnum;
use app\service\cdc\AccountChangeService;
use app\service\notice\feishu\FeiShuWebHookService;
use app\service\notice\NoticeService;
use think\console\Input;
use think\console\Output;
use think\Exception;
use think\facade\Cache;

class AccountChangeWork extends BaseWork
{
    protected function configure()
    {
        // 指令配置
        $this->setName('cdc_account_change_work');
        // 设置参数
        $this->setDescription('CDC-账户切换')
            ->setHelp('php think cdc_account_change_work');
    }

    /**
     * @param Input $input
     * @param Output $output
     * @return false|void
     * @throws Exception
     */
    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        $this->getOutputMessage('账户切换数据修复开始');
        $redis = Cache::store('redis')->handler();
        $redisKey = CdcEnum::CDC_ACCOUNT_CHANGE_LIST;
        $t = time();
        $runTime = 5 * 60;
        $notice = NoticeService::getInstance(NoticeEnum::NOTICE_TYPE_FS_WEBHOOK, NoticeEnum::FEI_SHU_WEBHOOK['cdc']);
        if (! $notice instanceof FeiShuWebHookService) {
            $this->getOutputMessage('飞书WebHook通知获取失败');
            return false;
        }
        while (time() - $t <= $runTime) {
            $info = trim($redis->lpop($redisKey));
            if (! $info) {
                sleep(10);
                continue;
            }
            $obj = new AccountChangeService();
            try {
                if (! $obj->startChange($info)) {
                    throw new Exception($obj::getError(0));
                }
                $this->getOutputMessage('account[' . $info . '] 成功');
            } catch (\Exception $e) {
                $this->getOutputMessage('account[' . $info . '] 错误：' . $e->getMessage());
                $notice->sendSingleMessage(['msg' => $e->getMessage(), 'title' => '账户切换预警']);
                echo $e->getLine() . PHP_EOL;
                echo $e->getFile() . PHP_EOL;
                echo $e->getTraceAsString() . PHP_EOL;
                $redis->rpush($redisKey, $info);
                sleep(10);
            }
        }
        $this->getOutputMessage('账户切换数据修复结束');
    }
}
